package com.sxkf.core.third.os.impl;

import cn.hutool.core.date.DateTime;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.sxkf.core.third.os.OsConstant;
import com.sxkf.core.third.os.OsService;
import com.sxkf.core.third.os.vo.response.UploadFileVO;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * @Description 阿里OSS存储
 * @Author Eliauk
 * @Date 2023/5/26 4:50 PM
 */
@Service
@Data
@ConfigurationProperties(prefix = "aliyun-oss")
public class OssServiceImpl implements OsService {

    /**
     * 上传文件
     *
     * @param file 文件
     * @return UploadFileVO
     */
    @Override
    public UploadFileVO uploadFile(MultipartFile file) throws IOException {
        OSS ossClient = new OSSClientBuilder().build(OsConstant.END_POINT, OsConstant.KEY, OsConstant.SECRET);
        InputStream inputStream = file.getInputStream();
        String fileName = file.getOriginalFilename();
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        fileName = uuid + fileName;
        String datePath = new DateTime().toString("yyyy/MM/dd");
        fileName = datePath + "/" + fileName;
        ossClient.putObject(OsConstant.BUCKET_NAME, fileName, inputStream);
        ossClient.shutdown();
        UploadFileVO uploadFileVO = new UploadFileVO();
        uploadFileVO.setUrl("https://" + OsConstant.BUCKET_NAME + "." + OsConstant.END_POINT + "/" + fileName);
        return uploadFileVO;
    }

}
